/*
    Copyright (c) Guangzhou Data Control Network Technology Co., Ltd. All rights reserved.
    Licensed under the MIT License.
    function: 生成图片的脚本
    contact:dcdev_founder@foxmail.com
*/
(function (window, undefined) {
    var counter = 0;
    draw_canvas = {
        // 显示loading
        draw: function (data) {
            $("body").append(
                `<canvas id="_dc_canvas_container_" width="${$(`#${data.id}`).width()}" height="${$(`#${data.id}`).height()}" style="display:none;"></canvas>`
            );
            var ctx = document.getElementById("_dc_canvas_container_").getContext("2d");
            var array = data.draw_config;
            for (let index = 0; index < array.length; index++) {
                const element = array[index];
                switch (element.type) {
                    case "qrcode":
                        counter++;
                        console.log("download counter:", counter);
                        $.getScript("https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js",
                            function () {
                                $.getScript(
                                    "https://cdn.staticfile.org/jquery.qrcode/1.0/jquery.qrcode.min.js",
                                    function () {
                                        var _div_ = new Date().getTime();
                                        var _img_ = new Date().getTime() + 11;
                                        $("body").append(
                                            `<div id="${_div_}" style="display:none;"></div><img id="${_img_}" style="top:-1000px;height:100%;opacity:0.5;"/>`
                                        )
                                        var qrcode = $(`#${_div_}`).qrcode(
                                            element.url).hide();
                                        var canvas = qrcode.find('canvas').get(0);
                                        var image = document.getElementById(_img_);
                                        // 指定格式 PNG 图片后缀可自定义
                                        image.src = canvas.toDataURL("image/png");
                                        image.style = "height:100%";

                                        $(`#${_img_}`).load(function () {
                                            ctx.beginPath();
                                            ctx.drawImage($(this)[0], element.position
                                                .x, element
                                                    .position.y,
                                                element.position.w, element.position
                                                .h);
                                            ctx.stroke();
                                            this.remove();
                                            counter--;
                                            console.log("download counter:", counter);
                                        })
                                    })
                            })
                        break;
                    case "rect":
                        if (element.fillStyle)
                            ctx.fillStyle = element.fillStyle;
                        if (element.strokeStyle)
                            ctx.strokeStyle = element.strokeStyle;
                        if (element.lineWidth)
                            ctx.lineWidth = element.lineWidth;
                        if (element.fillRect)
                            ctx.fillRect(element.fillRect.x, element.fillRect.y, element.fillRect.w,
                                element
                                    .fillRect.h);
                        if (element.strokeRect)
                            ctx.strokeRect(element.strokeRect.x, element.strokeRect.y, element
                                .strokeRect.w,
                                element
                                    .strokeRect.h);
                        if (element.clearRect)
                            ctx.clearRect(element.clearRect.x, element.clearRect.y, element.clearRect.w,
                                element
                                    .clearRect.h);
                        break;
                    case "line":
                        ctx.beginPath();
                        if (element.fillStyle)
                            ctx.fillStyle = element.fillStyle;
                        if (element.strokeStyle)
                            ctx.strokeStyle = element.strokeStyle;
                        if (element.lineWidth)
                            ctx.lineWidth = element.lineWidth;
                        if (element.lineJoin)
                            ctx.lineJoin = element.lineJoin;
                        if (element.lineCap)
                            ctx.lineCap = element.lineCap;

                        var line_array = element.position;
                        for (let index = 0; index < line_array.length; index++) {
                            const _element = line_array[index];
                            if (index == 0) {
                                ctx.moveTo(_element.x, _element.y);
                            } else {
                                ctx.lineTo(_element.x, _element.y);
                            }
                        }
                        // 如果需要填充颜色
                        if (element.fillStyle)
                            ctx.fill();
                        ctx.stroke();
                        break;
                    case "text":
                        ctx.beginPath();
                        ctx.font = element.size + "px";
                        ctx.fillStyle = element.color;
                        ctx.fillText(element.text, element.position.x, element.position.y);
                        ctx.stroke();
                        break;
                    case "block":
                        ctx.fillStyle = element.color;
                        ctx.fillRect(element.position.x, element.position.y, element.position.w, element
                            .position.h);
                        break;
                    case "img":
                        console.log("如果图片不能渲染请检查是否跨域")
                        // 动态添加img标签
                        var stamp = new Date().getTime();
                        $("body").append(
                            `<img id="${stamp}" src="${element.src}" style="display:none;">`)
                        counter++;
                        $(`#${stamp}`).load(function () {
                            ctx.beginPath();
                            ctx.drawImage($(this)[0], element.position.x, element
                                .position.y,
                                element.position.w, element.position.h);
                            ctx.stroke();
                            // 移除添加的img标签
                            this.remove();
                            counter--;
                            console.log("download counter:", counter);
                        })
                        break;
                }
            }
            if (counter == 0) {
                document.getElementById(data.id).src = this.canvas_to_image(document.getElementById(
                    "_dc_canvas_container_"), data.format, data.quality).src;
                $("#_dc_canvas_container_").remove();
            } else {
                console.log("download counter:", counter);
                var interval = setInterval(() => {
                    if (counter == 0) {
                        clearInterval(interval);
                        document.getElementById(data.id).src = this.canvas_to_image(document
                            .getElementById("_dc_canvas_container_"), data.format, data.quality).src;
                        $("#_dc_canvas_container_").remove();
                    }
                }, 50);
            }
        },
        // 把image 转换为 canvas对象
        image_to_canvas: function (image) {
            // 创建canvas DOM元素，并设置其宽高和图片一样
            var canvas = document.createElement("canvas");
            canvas.width = image.width;
            canvas.height = image.height;
            // 坐标(0,0) 表示从此处开始绘制，相当于偏移。
            canvas.getContext("2d").drawImage(image, 0, 0);
            return canvas;
        },
        // 从 canvas 提取图片 image
        canvas_to_image: function (canvas, format, quality) {
            var image = new Image();
            // 设置属性 crossOrigin
            image.setAttribute('crossOrigin', 'anonymous')
            if (format) {
                quality = quality ? quality : 0.8;
                image.src = canvas.toDataURL("image/jpg", quality);
            }
            else {
                image.src = canvas.toDataURL("image/png");
            }
            return image;
        }
    }
})(window);
